
#include <stdio.h>
#include <string.h>
#include "appload.h"
#include "sysdef.h"
#include "device.h"
#include "flash.h"
#include "vfs.h"

extern char __flash_user_start[];
extern char __flash_user_end[];

void fs_test(void *argv) {
    UNUSED(argv);

    FILE *fp = NULL;
    int n = 0;
    char buf[16] = {0};

    printf("file test start\n");

    if((fp = fopen("/littlefs0/test.txt", "r")) == NULL) {
        printf("warn: file may not exist\n");
        goto write;
    } else {
        n = fread(buf, 1, 16, fp);
        if(n < 0) {
            printf("error: file read failed\n");
        } else {
            printf("read data: %s\n", buf);
        }

        goto end;
    }

write:
    if((fp = fopen("/littlefs0/test.txt", "w")) == NULL) {
        printf("error: file created failed\n");
        goto end;
    } else {
        printf("new file created\n");
    }

    n = fwrite("hello, world", 1, strlen("hello, world"), fp);
    if(n <= 0) {
        printf("error: file write failed\n");
        goto end;
    } else {
        printf("file write ok\n");
    }

end:
    if(fp)
        fclose(fp);
}

dev_export(DEV_CLASS_FLASH, CONFIG_FLASH_ONCHIP_NAME, FLASH_TYPE_ONCHIP);
vfs_lfs_export(CONFIG_LFS_ROOT_DIR_NAME_USE_FLASH_ONCHIP, 0, __flash_user_start, __flash_user_end);
app_export(fs_test, NULL, "fs_test", 16384, 30, 1);
